package fr.ensisa.sunspot.actor.osc;

import java.net.Socket;
import java.util.Vector;

import fr.ensisa.sunspot.actor.AbstractActor;
import fr.ensisa.sunspot.actor.IActor;
import fr.ensisa.sunspot.actor.Template;
import fr.ensisa.sunspot.event.IEvent;

public class OscActor extends AbstractActor {
	private static final long serialVersionUID = 158946330199457896L;
	
	public static final String HOST = "127.0.0.1";
	public static final int PORT = 7000;
	
	private Vector<IEvent> outgoingEvents;
	private OscSocket oscSocket;
	
	public OscActor(Socket s) {
		super(IActor.KIND_FILTER);
		
		this.setGeneratedEvents(this.getOutgoingEvents());
		
		this.oscSocket = new OscSocket(s);
		
		this.setTemplate(this.oscSocket.readTemplate());
		
		new Thread(this.oscSocket).start();
	}
	
	public OscActor(Template actorTemplate, Template serverTemplate) {
		super(IActor.KIND_FILTER);
		
		this.setGeneratedEvents(this.getOutgoingEvents());
		
		this.setTemplate(actorTemplate);
		this.oscSocket = new OscSocket(HOST, PORT, serverTemplate);
		
		new Thread(this.oscSocket).start();
	}
	
	public Vector<IEvent> getOutgoingEvents() {
		if(this.outgoingEvents == null)
			this.outgoingEvents = new Vector<IEvent>(20);
		
		return this.outgoingEvents;
	}

	@Override
	public int getID() {
		return 0;
	}

	@Override
	public int process(long timeStamp, IEvent event) {
		if(this.oscSocket.isClosed())
			return IActor.RETURN_REMOVEMEFROMTHELIST;
		
		if(event != null)
			this.oscSocket.sendEvent(event);
		
		if(this.oscSocket.isEmpty())
			return IActor.RETURN_DONOTHING;
		else {
			this.outgoingEvents.clear();
			this.outgoingEvents.addAll(this.oscSocket.getBuffer());
			return IActor.RETURN_GETMYEVENTSANDDONTKILLME;
		}
	}
}
